package UDP.chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class send {
    public static void main(String[] args) {
        DatagramSocket Socket = null;
        Scanner scanner = null;
        Boolean js =true;
        String sr = null;
        try {
            //1.给定地址端口
            Socket = new DatagramSocket(8090);
            //1.1给定ip和端口
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            int port = 8080;
            //2.接收数据
            new jsxc1(Socket).start();

            //发送消息
            scanner = new Scanner(System.in);
            while (js) {
                //System.out.print("使用nextLine方法：");
                if (scanner.hasNextLine()) {//scanner.hasNextLine() 判断用户输入是否结束，有没有输入字符串
                    //使用nextLine接收数据
                    sr = scanner.nextLine();
                    if (sr.equals("^")) {
                        System.out.println("111");
                        js = false;
                        scanner.close();
                    } else {
                        //2.3把数据打包
                        DatagramPacket Packet = new DatagramPacket(sr.getBytes(), 0, sr.getBytes().length, ip, port);
                        //3发送包
                        Socket.send(Packet);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            scanner.close();
        }
    }
}

class jsxc1 extends Thread {
    private DatagramSocket Socket = null;
    private Boolean js = true;
    public jsxc1() {

    }
    public jsxc1(DatagramSocket Socket){
        this.Socket=Socket;
    }

    @Override
    public void run() {
        try {
            while (js){
                byte[] buffer = new byte[1024];//字节大小
                DatagramPacket Packet = new DatagramPacket(buffer, 0, buffer.length);//创建包用来存放收到的包
                Socket.receive(Packet);//阻塞接收
                //2.2打印包中的数据
                System.out.print(Packet.getAddress()+"：");//获取是谁发送到
                System.out.println(new String(Packet.getData(), 0, Packet.getLength()));//获取发送的内容

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            Socket.close();
        }

    }
}
